package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorsMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.service.DishService;
import com.sky.utils.UserThreadLocalUtil;
import com.sky.vo.DishVO;
import com.sky.vo.PageResult;
import io.netty.handler.codec.MessageAggregationException;
import org.springframework.beans.BeanUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * PROJECT_NAME: sky-take-out
 * NAME: DishServiceImpl
 *
 * @AUTHOR: zhang
 * DATE: 2023/11/23
 * DESCRIPTION :
 */
@Service
public class DishServiceImpl implements DishService {
    @Resource
    private DishMapper dishMapper;
    @Resource
    private DishFlavorsMapper dishFlavorsMapper;
    @Resource
    private SetmealDishMapper setmealDishMapper;
    @Resource
    private SetmealMapper setmealMapper;

    /**
     * 菜品分页
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult getPage(DishPageQueryDTO dto) {
        //分页
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        //条件查询
        Page<DishVO> page = dishMapper.getPage(dto);
        //封装数据
        PageResult pageResult = PageResult.builder().total(page.getTotal()).records(page.getResult()).build();
        return pageResult;
    }

    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertDish(DishDTO dishDTO) {
        //1、添加菜品基本信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //补齐字段
        dish.setCreateTime(LocalDateTime.now());
        dish.setUpdateTime(LocalDateTime.now());
        Long userId = UserThreadLocalUtil.getUser();
        dish.setCreateUser(userId);
        dish.setUpdateUser(userId);

        dishMapper.insertDish(dish);
        //2、添加菜品口味
        Long dishId = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (Objects.nonNull(flavors) && flavors.size() > 0) {
            for (DishFlavor flavor : flavors) {
                String name = flavor.getName();
                String value = flavor.getValue();
                dishFlavorsMapper.insertDishFlavors(dishId, name, value);
            }
        }
    }

    /**
     * 根据id查询菜品
     * @param id
     */
    @Override
    public DishVO selectDishById(Long id) {
        DishVO dishVO = dishMapper.selectDishById(id);
        //根据菜品id查询口味
        List<DishFlavor> dishFlavors = dishFlavorsMapper.selectDishFlavorsByDishId(id);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    /**
     * 修改菜品信息
     * @param dishDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDish(DishDTO dishDTO) {
        //1.修改菜品基本信息
        dishMapper.updateDish(dishDTO);

        //2.修改菜品口味
        //删除菜品口味
        dishFlavorsMapper.deleteDishFlavorByDishId(dishDTO.getId());
        //添加菜品口味
        List<DishFlavor> dishFlavorList = dishDTO.getFlavors();
        if (!dishFlavorList.isEmpty()){
            for (DishFlavor dishFlavor : dishFlavorList) {
                String name = dishFlavor.getName();
                String value = dishFlavor.getValue();
                dishFlavorsMapper.insertDishFlavors(dishDTO.getId(),name,value);
            }
        }

    }

    /**
     * 批量删除菜品
     * @param ids 要删除的菜品id集合
     */
    @Override
    public void deleteBatchDish(List<Long> ids) {
        //查看菜品的状态，在售状态不能删除
        for (Long dishId : ids) {
            DishVO dishVO = dishMapper.selectDishById(dishId);
            Integer status = dishVO.getStatus();
            if (status.equals(StatusConstant.ENABLE)){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
            //todo:被套餐关联的菜品不能删除
            //根据菜品id查询套餐菜品关联信息
            List<SetmealDish> setmealDishList = setmealDishMapper.selectSetmealDishByDishId(dishId);
            if (!setmealDishList.isEmpty()){
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        }
            dishMapper.deleteBatch(ids);
    }

    /**
     * 根据分类id查询菜品信息
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> selectDishByCategoryId(Long categoryId) {
        return dishMapper.selectDishByCategoryId(categoryId);
    }

    @Override
    public void updateDishStatus(Integer status,Long id) {
        //菜品停售则包含菜品的套餐同时停售
        if (status.equals(StatusConstant.DISABLE)){
            //根据菜品id查看套餐菜品关联信息
            List<SetmealDish> setmealDishList = setmealDishMapper.selectSetmealDishByDishId(id);
            if (!setmealDishList.isEmpty()){
                for (SetmealDish setmealDish : setmealDishList) {
                    //获取套餐id
                    Long setmealId = setmealDish.getSetmealId();
                    //根据套餐id修改套餐状态
                    Setmeal setmeal = new Setmeal();
                    setmeal.setId(setmealId);
                    setmeal.setStatus(StatusConstant.DISABLE);
                    setmealMapper.update(setmeal);
                }
            }
        }
        //更新菜品状态
        DishDTO dishDTO = new DishDTO();
        dishDTO.setId(id);
        dishDTO.setStatus(status);
        dishMapper.updateDish(dishDTO);
    }

    /**
     * 根据分类id查询菜品信息+口味
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> selectDishAndFlavoByCategoryId(Long categoryId) {
        //根据分类id查询菜品基本信息
        List<Dish> dishList = dishMapper.selectDishByCategoryId(categoryId);

        List<DishVO> dishVOList = new ArrayList<>();
        for (Dish dish : dishList) {
            Long dishId = dish.getId();
            //根据菜品id查询菜品口味关联信息
            List<DishFlavor> dishFlavorList = dishFlavorsMapper.selectDishFlavorsByDishId(dishId);
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            dishVO.setFlavors(dishFlavorList);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
